﻿using System.Threading;

namespace Noria.Web.MyMSDN
{
    /// <summary>
    /// Provide a quick way to get if an event wait handle is set or not
    /// </summary>
    public class AsyncWaiter : EventWaitHandle
    {
        public AsyncWaiter()
            : base(false, EventResetMode.ManualReset)
        {
        }

        /// <summary>
        /// True indicates the current event wait handle is still waiting for
        /// the corresponding thread running complete; False means it was set.
        /// </summary>
        public bool IsAlive { get { return !WaitOne(0, false); } }

        /// <summary>
        /// Sleep a while
        /// 
        /// Return true means the event waiter has not been set after the period of sleeping
        /// </summary>
        public bool Sleep(int millisecondsTimeout)
        {
            return !WaitOne(millisecondsTimeout, false);
        }

        /// <summary>
        /// Sleep a while
        /// 
        /// Return true means none of the event waiter has been set after the period of sleeping
        /// </summary>
        public static bool Sleep(int millisecondsTimeout, params WaitHandle[] waiters)
        {
            return WaitTimeout == WaitAny(waiters, millisecondsTimeout);
        }
    }
}